#!/system/bin/sh
# Validate settings.ini
if ! sh -n /data/adb/box/settings.ini 2>"/data/adb/box/run/settings_err.log"; then
  echo "err: settings.ini contains a syntax error" | tee -a "/data/adb/box/run/settings_err.log"
  exit 1
fi

export PATH="/data/adb/magisk:/data/adb/ksu/bin:/data/adb/ap/bin:$PATH:/data/data/com.termux/files/usr/bin"

module_dir="/data/adb/modules/box_for_root"
base_dir="/data/adb/box"
variab_dir="${base_dir}/run/variab"
log_file="${base_dir}/run/Networkswitch_debug.log"
log_file_path="/data/local/tmp/"
temp_log_file="${log_file_path}debug.log.tmp"
last_check_file="${variab_dir}/last_check_time"
last_wifi_state_file="${variab_dir}/last_wifi_state"

if [ ! -d "$variab_dir" ]; then
    mkdir -p "$variab_dir"
fi

scripts=$(realpath "$0")
scripts_dir=$(dirname "${scripts}")

events=$1
if [ "$events" != "w" ]; then
    return
fi

source "${base_dir}/settings.ini"

if [ "$enable_network_service_control" != "true" ]; then
    exit 0
fi

source "${scripts_dir}/ctr.utils"

service_script="${scripts_dir}/box.service"
iptables_script="${scripts_dir}/box.iptables"

log_msg() {
    if [ "$inotify_log_enabled" = "true" ]; then
        if [ -z "$1" ]; then
            echo "" >> "$log_file"
        else
            echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$log_file"
        fi
    fi
}

clean_old_logs() {
    # Only keep logs from the past 24 hours
    local retention_seconds=86400 # 24 hours
    local cutoff_time=$(( $(date +%s) - retention_seconds ))
    local cutoff_str
    cutoff_str=$(date -d "@${cutoff_time}" '+%Y-%m-%d %H:%M:%S')

    if [ -f "$log_file" ]; then
        awk -v cutoff="$cutoff_str" '
            !/^[0-9]{4}-[0-9]{2}-[0-9]{2}/ {print; next}
            substr($0, 1, 19) >= cutoff {print}
        ' "$log_file" > "$temp_log_file" && mv "$temp_log_file" "$log_file"
    fi
}
clean_old_logs

current_time=$(date +%s)
last_check_time=0
if [ -f "$last_check_file" ]; then
    last_check_time=$(cat "$last_check_file")
fi

time_diff=$((current_time - last_check_time))
stability_window=3

if [ "$time_diff" -lt "$stability_window" ]; then
    log_msg "Skip check: (${time_diff}s), within stability window"
    return
fi

echo "$current_time" > "$last_check_file"

wifi_status=$(is_wifi_connected)
ssid=$(get_current_ssid)

get_current_ip() {
    ip addr show wlan0 | grep 'inet ' | awk '{print $2}' | cut -d/ -f1
}

check_module_service() {
    if [ "$enable_network_service_control" = "true" ]; then
        if [ -f "$box_pid" ]; then
            current_state="enabled"
        else
            current_state="disabled"
        fi

        last_ssid=""
        last_ip=""
        if [ -f "$last_wifi_state_file" ]; then
            last_ssid=$(grep 'ssid:' "$last_wifi_state_file" | cut -d: -f2)
            last_ip=$(grep 'ip:' "$last_wifi_state_file" | cut -d: -f2)
        fi

        if [ "$wifi_status" = "wifi" ] && [ -n "$ssid" ]; then
            for i in {1..3}; do
                current_ip=$(get_current_ip)
                if [ -n "$current_ip" ]; then
                    break
                fi
                sleep 2
            done

            if [ -n "$current_ip" ]; then
                echo "-- Notifikasi LOG --" > "$log_file"
                log_msg "--- Network state change: WiFi connected ---"
                log_msg "SSID: ${ssid}, IP: ${current_ip}"
                echo "ssid:${ssid}" > "$last_wifi_state_file"
                echo "ip:${current_ip}" >> "$last_wifi_state_file"
                
                if [ "$use_module_on_wifi" = "false" ]; then
                    log_msg "Policy: Disable service when on WiFi"
                    if [ "$current_state" != "disabled" ]; then
                        "$iptables_script" disable
                        "$service_script" stop
                        log_msg "Action: Service stopped"
                    else
                        log_msg "State: Service already stopped, no action needed"
                    fi
                else
                    if [ "$use_ssid_matching" = "true" ]; then
                        if [ "$use_wifi_list_mode" = "blacklist" ]; then
                            log_msg "Policy: WiFi blacklist mode, list: ${wifi_ssids_list}"
                            if is_allowed_wifi "$ssid" "$wifi_ssids_list"; then
                                log_msg "Result: ${ssid} is in blacklist"
                                if [ "$current_state" != "disabled" ]; then
                                    "$iptables_script" disable
                                    "$service_script" stop
                                    log_msg "Action: Service stopped"
                                else
                                    log_msg "State: Service already stopped, no action needed"
                                fi
                            else
                                log_msg "Result: ${ssid} not in blacklist"
                                if [ "$current_state" != "enabled" ]; then
                                    "$service_script" start
                                    "$iptables_script" enable
                                    log_msg "Action: Service started"
                                else
                                    log_msg "State: Service already running, no action needed"
                                fi
                            fi
                        elif [ "$use_wifi_list_mode" = "whitelist" ]; then
                            log_msg "Policy: WiFi whitelist mode, list: ${wifi_ssids_list}"
                            if is_allowed_wifi "$ssid" "$wifi_ssids_list"; then
                                log_msg "Result: ${ssid} is in whitelist"
                                if [ "$current_state" != "enabled" ]; then
                                    "$service_script" start
                                    "$iptables_script" enable
                                    log_msg "Action: Service started"
                                else
                                    log_msg "State: Service already running, no action needed"
                                fi
                            else
                                log_msg "Result: ${ssid} not in whitelist"
                                if [ "$current_state" != "disabled" ]; then
                                    "$iptables_script" disable
                                    "$service_script" stop
                                    log_msg "Action: Service stopped"
                                else
                                    log_msg "State: Service already stopped, no action needed"
                                fi
                            fi
                        else
                            log_msg "Warning: Unknown WiFi list mode, using default start logic"
                            if [ "$current_state" != "enabled" ]; then
                                "$service_script" start
                                "$iptables_script" enable
                                log_msg "Action: Service started"
                            else
                                log_msg "State: Service already running, no action needed"
                            fi
                        fi
                    else
                        log_msg "Policy: Default behavior is to start service on WiFi"
                        if [ "$current_state" != "enabled" ]; then
                            "$service_script" start
                            "$iptables_script" enable
                            log_msg "Action: Service started"
                        else
                            log_msg "State: Service already running, no action needed"
                        fi
                    fi
                fi
            else
                log_msg "--- Network state change: WiFi connecting ---"
                log_msg "State: No valid IP address yet, skipping action"
            fi

        elif [ "$wifi_status" = "not_wifi" ]; then
            log_msg "--- Network state change: WiFi disconnected ---"
            if [ "$use_module_on_wifi_disconnect" = "true" ]; then
                log_msg "Policy: Start service when WiFi disconnected"
                if [ "$current_state" != "enabled" ]; then
                    "$service_script" start
                    "$iptables_script" enable
                    log_msg "Action: Service started"
                else
                    log_msg "State: Service already running, no action needed"
                fi
            else
                log_msg "Policy: Disable service when WiFi disconnected"
                if [ "$current_state" != "disabled" ]; then
                    "$iptables_script" disable
                    "$service_script" stop
                    log_msg "Action: Service stopped"
                else
                    log_msg "State: Service already stopped, no action needed"
                fi
            fi
        fi
    else
        log_msg "Network control module service is disabled!"
        return
    fi
}

check_module_service